<?php
/**
 * Talents come from diligence, and knowledge is gained by accumulation.
 *
 * @author: 晋<657306123@qq.com>
 */

namespace app\common\support;

use app\common\exception\WechatException;

class WechatValidate{

	/**
	 * 验证是否通过，否则抛出异常
	 *
	 * @param mixed $result
	 * @return mixed
	 * @throws \app\common\exception\WechatException
	 */
	public static function validate($result){
		if(!self::isOk($result)){
			self::throwException($result);
		}

		return $result;
	}

	/**
	 * 验证是否通过
	 *
	 * @param mixed $result
	 * @return bool
	 */
	public static function isOk($result){
		if(!is_array($result)){
			return true;
		}

		if(isset($result['errcode']) && $result['errcode'] != 0){
			return false;
		}

		return true;
	}

	/**
	 * 获取错误信息
	 *
	 * @param mixed $result
	 * @return string
	 */
	protected static function getErrMsg($result){
		if(!is_array($result)){
			return '';
		}

		if(isset($result['errmsg'])){
			return $result['errmsg'];
		}

		return '';
	}

	/**
	 * 获取错误码
	 *
	 * @param mixed $result
	 * @return int
	 */
	protected static function getErrCode($result){
		if(!is_array($result)){
			return 0;
		}

		if(isset($result['errcode'])){
			return $result['errcode'];
		}

		return 0;
	}

	/**
	 * 抛出异常
	 *
	 * @param mixed $result
	 * @throws \app\common\exception\WechatException
	 */
	protected static function throwException($result){
		$e = new WechatException(
			self::getErrMsg($result),
			self::getErrCode($result)
		);

		$e->setResponse($result);

		throw $e;
	}
}
